package com.android.pingpong;

import java.util.Random;
import java.util.Stack;

import com.android.pingpong.Cell;

public class Maze {

	private static final long serialVersionUID = 1L;
	final static int WIDTH = 300;
	final static int HEIGHT = 250;
	
	public boolean exitFound = false;
	static Random generator = new Random();
			
	public static Cell visitCell(Stack<Cell> visited, Cell[][] maze, Cell cell, int xsize, int ysize) {
		
		boolean triedLeft = false;
		boolean triedRight = false;
		boolean triedUp = false;
		boolean triedDown = false;
		cell.out = false;

		do {
			
			int direction = generator.nextInt(4);
			if (direction == 0)
				triedLeft = true;
			if (direction == 1)
				triedRight = true;
			if (direction == 2)
				triedUp = true;
			if (direction == 3)
				triedDown = true;

			// left
			if (direction == 0 && cell.x > 0) {
				Cell left = maze[cell.x - 1][cell.y];
				if (left != null && left.out) {
					left.right = cell;
					cell.left = left;					
					visited.push(cell);
					return left;					
				}
			}
			// right
			else if (direction == 1 && cell.x < xsize - 1) {
				Cell right = maze[cell.x + 1][cell.y];
				if (right != null && right.out) {
					right.left = cell;
					cell.right = right;					
					visited.push(cell);
					return right;
				}
			}
			// up
			else if (direction == 2 && cell.y > 0) {
				Cell up = maze[cell.x][cell.y - 1];
				if (up != null && up.out) {
					up.down = cell;
					cell.up = up;					
					visited.push(cell);
					return up;
				}
			}
			// down
			else if (direction == 3 && cell.y < ysize - 1) {
				Cell down = maze[cell.x][cell.y + 1];
				if (down != null && down.out) {
					down.up = cell;
					cell.down = down;					
					visited.push(cell);
					return down;
				}
			}
		}
		while (!(triedLeft && triedRight && triedUp && triedDown));

		return visited.isEmpty() ? null : visited.pop();
	}
	
	public static Cell[][] backTracker(int xsize, int ysize) {
		Cell[][] maze = new Cell[xsize][ysize];
		for (int x = 0; x < xsize; x++) {
			for (int y = 0; y < ysize; y++) {
				maze[x][y] = new Cell(x, y);
			}
		}
		
		Stack<Cell> visited = new Stack<Cell>();
		Cell current = maze[0][0];
		current.left = new Cell(-1,-1);
		maze[xsize-1][ysize-1].right = new Cell(-1,-1);
		
		do {			
			current = visitCell(visited, maze, current, xsize, ysize);			
		} while(current != null);
		return maze;
	}
	
	public static Cell[][] emptyMaze(int xsize, int ysize) {
		Cell[][] maze = new Cell[xsize][ysize];
		for (int x = 0; x < xsize; x++) {
			for (int y = 0; y < ysize; y++) {
				maze[x][y] = new Cell(x, y);
			}
		}
		return maze;
	}
	
	
	public Maze() throws Exception {
		//renderMaze(init(), backTracker(xsize, ysize), xsize, ysize);
	}
	
	public static void main(String[] args) throws Exception {
		new Maze();
	}
}


